import * as dictData from './dict.js'
import { localToRemoteCode } from './dictCodeLocalToRemote.js'
import {
    GET_CODE_LIST
} from '@api/url'
import ajax from '@api/ajax'

/**
 * 获取代码值列表
 * @param mode 取值模式 local本地  remote远程
 * @param code 代码编号
 * @returns {*|Array} 代码值列表
 */
export const getCodeList = function (mode = 'local', code) {
    return new Promise((resolve, reject) => {
            if (mode === 'local') {
                resolve(dictData[code] || [])
            } else if (mode === 'remote') {
                const remoteCode = localToRemoteCode(code)

                ajax.post(GET_CODE_LIST, {
                    paramIdx: remoteCode
                }).then(res => {
                    const resData = res.data || []
                    let resultList = []
                    for (let resDataItem of resData) {
                        resultList.push({
                            key: resDataItem.codeValue,
                            value: resDataItem.codeDesc
                        })
                    }
                    resolve(resultList)
                }).catch(err => {
                    console.error('查询代码失败！', err)
                    reject(err)
                })
            }
        }
    )
}

/**
 * 从特定代码值列表中找到对应的值
 * @param code 代码编号
 * @param key 特定key
 * @returns {null}
 */
export const getCodeKeyValue = function (mode = 'local', code, key) {
    return new Promise((resolve, reject) => {
        const promise = getCodeList(mode, code)
        promise.then(codeList => {
            for (const codeItem of codeList) {
                if (codeItem.key === key) {
                    resolve(codeItem.value)
                    return null
                }
            }
            resolve(null)
        }).catch(err => {
            reject(err)
        })
    })
}

/**
 * 获取代码值Map
 *
 * @param code 代码编号
 * @returns {{}} map字典
 */
export const getCodeMap = function (mode = 'local', code) {
    return new Promise((resolve, reject) => {
        const promise = getCodeList(mode, code)
        promise.then(codeList => {
            const codeMap = {}
            for (const codeItem of codeList) {
                codeMap[codeItem.key] = codeItem.value
            }
            resolve(codeMap)
        }).catch(err => {
            reject(err)
            resolve({})
        })
    })
}

export default {
    getCodeList,
    getCodeKeyValue,
    getCodeMap
}
